package cn.shengchao.examstar.gankao.http;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.util.Map;

/**
 * @program: examstarapi
 * @description: 赶考网请求封装
 * @author: Xiong weiqiang
 * @create: 2025-06-23 17:14
 */
public class GanKaoHttpRequest {
    public static String requestApi(String serverUrl,String uri, Map<String,Object> params, String appId, String appSecret){
        if (params==null){
            params=new java.util.HashMap<>();
        }
        params.put("app_id", appId);
        params.put("timestamp",System.currentTimeMillis());
        String token=GanKaoHttpParams.getSecretTokenByParams(params,appSecret);
        params.put("token",token);
        String paramsStr= HttpUtil.toParams(params);
        String requestUrl = serverUrl +uri+ "?"+paramsStr;
        HttpRequest request = HttpUtil.createGet(requestUrl);
        String result = request.execute().body();
        result=GanKaoHttpParams.unicodeEscapeToChinese( result);
        return result;
    }


    public static JSONObject getResultIfSuccess(String result){
        if (result!=null&& JSONUtil.isTypeJSON(result)){
            JSONObject jsonObject=new JSONObject( result);
            if (jsonObject.getInt("code")==10000||jsonObject.getInt("code")==10001||jsonObject.getInt("code")==10002){
                return jsonObject;
            }
        }
        System.err.println("赶考网请求交互失败："+ result);
        return null;
    }
}